import axios from "axios";

async function downloadImg(url) {
    let ret = new ArrayBuffer()
    await axios({
        url: url,
        responseType: 'arraybuffer'
    }).then(res => {
        ret = res.data
    })
    return ret
}

export default class feishu {
    constructor() {
        this.app_id = ""
        this.app_secret = ""
        this.tenant_access_token = ""
        this.host = "https://feishu.tju.ink"
        this.size = 4999
        this.sheetInfo = {}
        this.getAccessToken()
    }

    generateFeishuLink(url = "") {
        let spreadsheets = "";
        let spreadsheetToken = "";
        let pattern_spreadsheets = /sheets\/(.*)\?sheet=()/g;
        let pattern_spreadsheetToken = /sheet=(.*?)$/g;
        let list_spreadsheets = pattern_spreadsheets.exec(url);
        let list_spreadsheetToken = pattern_spreadsheetToken.exec(url);
        try {
            if (list_spreadsheets.length > 0) {
                spreadsheets = list_spreadsheets[1];
            }
        } catch (e) {
        }
        try {
            if (list_spreadsheetToken.length > 0) {
                spreadsheetToken = list_spreadsheetToken[1];
            }
        } catch (e) {
        }
        return {spreadsheets, spreadsheetToken}
    }

    // 获取tenant_access_token
    async getAccessToken() {
        let url = this.host + "/open-apis/auth/v3/tenant_access_token/internal/";
        await axios({
            method: "post",
            data: {
                "app_id": this.app_id, "app_secret": this.app_secret
            },
            url: url
        }).then((res) => {
            console.log("feishu-->", "getAccessToken:", res);
            this.tenant_access_token = res.data.tenant_access_token;
        })
    }

    // 获取表格信息
    async getSheetInfo(spreadsheets) {
        let url = this.host + "/open-apis/sheets/v2/spreadsheets/" + spreadsheets + "/metainfo";
        await axios({
            headers: {
                "Authorization": "Bearer " + this.tenant_access_token,
                "Content-Type": "application/json; charset=utf-8"
            },
            method: "get",
            url: url
        }).then((res) => {
            console.log("feishu-->", "getSheetInfo:", res);
        })
    }

    //读取单个范围
    async getSheetValuesByRange(spreadsheets, spreadsheetToken, range) {
        let url = this.host + "/open-apis/sheets/v2/spreadsheets/" + spreadsheets + "/values/" + spreadsheetToken + "!" + range
        let headers = {"Authorization": "Bearer " + this.tenant_access_token}
        let ret = ""
        await axios({
            headers: headers,
            method: "get",
            url: url
        }).then((res) => {
            console.log("feishu-->", "getSheetValuesByRange:", res);
            ret = res["data"]["data"]["valueRange"]["values"]
        })
        return ret;
    }

    // 向单个范围写入数据
    async setSheetValuesByRange(spreadsheets, spreadsheetToken, range, values) {
        let url = this.host + "/open-apis/sheets/v2/spreadsheets/" + spreadsheets + "/values";
        console.log(url)
        let headers = {
            "Authorization": "Bearer " + this.tenant_access_token,
            "Content-Type": "application/json; charset=utf-8"
        }
        let data = {
            "valueRange": {
                "range": spreadsheetToken + "!" + range,
                "values": values
            }
        }
        await axios({
            headers: headers,
            method: "put",
            data: data,
            url: url
        }).then((res) => {
            console.log("feishu-->", "setSheetValuesByRange:", res);
        })
    }

    // 向多个范围写入数据
    async setSheetValuesListByRange(spreadsheets, spreadsheetToken, range, valuesList) {
        let url = this.host + "/open-apis/sheets/v2/spreadsheets/" + spreadsheets + "/values"
        let headers = {"Authorization": "Bearer " + this.tenant_access_token}
        let data = {
            "valueRange": {
                "range": spreadsheetToken + "!" + range,
                "values": valuesList
            }
        }
        let ret = -1
        await axios({
            headers: headers,
            method: "put",
            data: data,
            url: url
        }).then((res) => {
            console.log("feishu-->", "setSheetValuesListByRange:", res);
            ret = res["data"]["code"]
        })
        if (ret == 0) {
            return true
        } else {
            return false
        }
    }

    // 设置单元格样式
    async setSheetStyleByRange(spreadsheets, spreadsheetToken, range, style = {}) {
        let url = this.host + "/open-apis/sheets/v2/spreadsheets/" + spreadsheets + "/style"
        let headers = {"Authorization": "Bearer " + this.tenant_access_token}
        let data = {
            "appendStyle": {
                "range": spreadsheetToken + "!" + range,
                "style": style
            }
        }
        let ret = -1
        await axios({
            headers: headers,
            method: "put",
            data: data,
            url: url
        }).then((res) => {
            console.log("feishu-->", "setSheetStyleByRange:", res);
            ret = res["data"]["code"]
        })
        if (ret == 0) {
            return true
        } else {
            return false
        }
    }

    // 合并单元格
    async setSheetCellsMerge(spreadsheets, spreadsheetToken, range) {
        let url = this.host + "/open-apis/sheets/v2/spreadsheets/" + spreadsheets + "/merge_cells"
        let headers = {"Authorization": "Bearer " + this.tenant_access_token}
        let data = {
            "range": spreadsheetToken + "!" + range,
            "mergeType": "MERGE_COLUMNS"
        }
        let code = -1
        await axios({
            headers: headers,
            method: "post",
            data: data,
            url: url
        }).then((res) => {
            console.log("feishu-->", "setSheetCellsMerge:", res);
            code = res["data"]["code"]
        })
        if (code == 0) {
            return true
        } else {
            return false
        }
    }

    // 写入图片
    async insertImage(spreadsheets, spreadsheetToken, range, imgUrl, name) {
        let url = this.host + "/open-apis/sheets/v2/spreadsheets/" + spreadsheets + "/values_image"
        let headers = {"Authorization": "Bearer " + this.tenant_access_token}
        let data = {
            "name": name + ".jpg",
            "range": spreadsheetToken + "!" + range,
        }
        await downloadImg(imgUrl).then(res => {
            console.log("res---------->", Array.prototype.slice.call(new Uint8Array(res)))
            data["image"] = Array.prototype.slice.call(new Uint8Array(res));
        })
        let code = -1
        await axios({
            headers: headers,
            method: "post",
            data: data,
            url: url
        }).then((res) => {
            console.log("feishu-->", "insertImage:", res);
            code = res["data"]["code"]
        })
        if (code == 0) {
            return true
        } else {
            return false
        }
    }
    /* 数字转字母 */
    createCol(n = 0) {
        const ordA = 'A'.charCodeAt(0)
        const ordZ = 'Z'.charCodeAt(0)
        const len = ordZ - ordA + 1
        let str = ""
        while (n >= 0) {
            str = String.fromCharCode(n % len + ordA) + str
            n = Math.floor(n / len) - 1
        }
        return str
    }

}
